<template>
  <div class="home">
    
      <div v-for="item of carts" :key="item.id">
        <van-card :price="item.productPrice" 
          :desc="item.productInfo" 
          :title="item.productName" 
          :thumb="item.productCover">
            <template #footer>
              <van-checkbox v-model="item.isSelected" 
              @click="handleItem" class="checkbox"></van-checkbox>
              <div>小计:{{item.productCount*item.productPrice | toFixed}}</div>
            </template>

            <template #num>
              <van-stepper v-model="item.productCount" />
            </template>
          </van-card>
      </div>
  <van-submit-bar
      button-text="提交订单" :price="carts | sum">
      <van-checkbox v-model="checkAll" 
      @click="changeAll" class="checkbox">全选</van-checkbox>
</van-submit-bar>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data(){
    return{
      checkAll: false,
      carts:[]
    }
  },
  filters:{
    toFixed(value) {
      return "$" + value.toFixed(2)
      // var arr = value.toFixed(2)
      // return arr
    },
    sum(val){
      if(val.length>0){
        var res = val.filter(function(item){
          console.log(res)
          return item.isSelected == true
        })
        var sum = 0;
        res.forEach(function(item){
          sum =sum+(item.productPrice*item.productCount)
        })
        return sum*100
      }
    },
  },
  mounted(){
    this.$http.get("/cart").then(res=>{
      this.carts = res.data
    })
    this.handleItem();
    this.checkAll = true
  },
  methods:{
    remove(index) {
        this.carts.splice(index, 1)
    },
    changeAll() {
        this.carts.forEach(item => item.isSelected = this.checkAll)
        /* var carts = this.$data.carts
        carts.forEach(item=>{
            item.isSelected = this.checkAll
            // return this.carts
        })
        // this.carts = carts */
    },
    handleItem(){
        this.checkAll = this.carts.every(item=>item.isSelected)
    },
    
  }
}
</script>

<style scope>
.home{
  position: relative;
}
.checkbox{
  position: absolute;
  left: 0;
  /* top: 50%;
  transform: translateY(-50%); */
}
</style>